package net.forsalemall.android;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.TextDrawable;
import com.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class EditAdActivity extends Activity {
	private View images;
	private EditText superCatView;
	private EditText catView;
	private TextView noticeView;
	private EditText adTextField;
	private EditText phoneNoField;

	private View.OnLongClickListener longClickListener;
	private List<Bitmap> bitmaps;
	private List<ImageItem> files;

	private Uri imageUri;
	private int counter = 0;
	private static final int GET_IMAGE_FROM_GALLERY = 0;
	private static final int GET_IMAGE_BY_CAMERS = 1;

	private String countryCode;
	private String phoneNo;
	private int adId;
	private String adDesc;
	private String[] fileNames;
	private String phonePrefix;

	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.edit_ad);
			final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
			actionBar.setTitle(getString(R.string.title_edit_post));
			adId = getIntent().getIntExtra(Constants.KEY_AD_ID, -1);
			adDesc = getIntent().getStringExtra(Constants.KEY_AD_TEXT);
			fileNames = getIntent().getStringArrayExtra(
					Constants.KEY_FILE_NAMES);
			countryCode = getIntent()
					.getStringExtra(Constants.KEY_COUNTRY_CODE);
			phoneNo = getIntent().getStringExtra(Constants.KEY_PHONE_NO);

			superCatView = (EditText) findViewById(R.id.super_category_spinner);
			catView = (EditText) findViewById(R.id.category_spinner);
			JSONObject jo = new JSONObject(getIntent().getStringExtra(
					Constants.KEY_CAT_INFO));
			superCatView.setText(Utils.getDecodedString(jo
					.getString("sup_cat_name")));
			catView.setText(Utils.getDecodedString(jo.getString("cat_name")));
			actionBar.setHomeAction(new Action() {

				public void performAction(View view) {
					backToHome();
				}

				public int getDrawable() {
					// TODO Auto-generated method stub
					return R.drawable.ic_title_home_default;
				}
			});
			actionBar.setDisplayHomeAsUpEnabled(true);

			findViewById(R.id.button_pick_by_camera).setOnClickListener(
					new View.OnClickListener() {
						public void onClick(View v) {
							takePicture();
						}
					});
			findViewById(R.id.button_pick_from_gallery).setOnClickListener(
					new View.OnClickListener() {
						public void onClick(View v) {
							pickFromGallery();
						}
					});

			noticeView = (TextView) findViewById(R.id.notice_view);
			adTextField = (EditText) findViewById(R.id.ad_text_field);
			phoneNoField = (EditText) findViewById(R.id.phone_no_field);
			phonePrefix = Constants.COUNTRY_CODE_KUWAIT.equals(countryCode) ? Constants.PHONE_CODE_KUWAIT
					: Constants.PHONE_CODE_UAE;
			TextDrawable td = new TextDrawable(phonePrefix + "-");
			td.setTextSize(phoneNoField.getTextSize());
			phoneNoField.setCompoundDrawablesWithIntrinsicBounds(td, null,
					null, null);
			int phoneDigit = Constants.COUNTRY_CODE_KUWAIT.equals(countryCode) ? Constants.NUMBER_OF_PHONE_DIGIT_KUWAIT
					: Constants.NUMBER_OF_PHONE_DIGIT_UAE;
			InputFilter[] FilterArray = new InputFilter[1];
			FilterArray[0] = new InputFilter.LengthFilter(phoneDigit);
			phoneNoField.setFilters(FilterArray);
			if ((phoneNo != null) && (phoneNo.length() > phonePrefix.length())) {
				phoneNoField.setText(phoneNo.substring(phonePrefix.length()));
			}

			adTextField.setText(adDesc);

			images = findViewById(R.id.images_container);
			bitmaps = new ArrayList<Bitmap>();
			files = new ArrayList<ImageItem>();
			findViewById(R.id.button_edit).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							update();
						}
					});
			findViewById(R.id.button_sold).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							markSold();
						}
					});

			longClickListener = new View.OnLongClickListener() {

				public boolean onLongClick(View view) {
					final View v = view;
					AlertDialog.Builder bb = new AlertDialog.Builder(
							EditAdActivity.this);
					bb.setMessage(getString(R.string.delete_confirmation_message));
					bb.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									removeImage(v);
								}
							});
					bb.setNegativeButton(getString(R.string.no),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
								}
							});
					bb.show();
					return true;
				}
			};
			images.findViewById(R.id.image_item1).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item2).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item3).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item4).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item5).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item6).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item7).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item8).setOnLongClickListener(
					longClickListener);
			images.findViewById(R.id.image_item9).setOnLongClickListener(
					longClickListener);
			loadPreviousImages();
			// showImages();
			// showPostTypeOptions();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadPreviousImages() {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(
							EditAdActivity.this, null,
							getString(R.string.loading));
					progressDialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					if (fileNames != null) {
						Bitmap bitmap;
						for (int i = 0; i < fileNames.length; i++) {
							bitmap = HttpUtils.downloadFile(HttpUtils
									.getFileUrl(
											Constants.getAdImgThumbDirName(),
											fileNames[i]), EditAdActivity.this);
							bitmaps.add(bitmap);
							files.add(new ImageItem(fileNames[i], false));
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					showImages();
					progressDialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	private void update() {
		try {
			String text = adTextField.getText().toString();
			if (files.size() < Constants.MIN_IMAGES) {
				Utils.showAlertMessage(this, null,
						getString(R.string.no_image_attached));
			} else if (text.length() == 0) {
				Utils.showAlertMessage(this, null,
						getString(R.string.no_text_attached));
			} else {
				update(text,
						(phonePrefix + (phoneNoField.getText().toString())));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void update(final String text, final String phNo) throws Exception {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;
			private String error;

			protected void onPreExecute() {
				try {
					progressDialog = Utils.getProgressDialog(
							EditAdActivity.this, null,
							getString(R.string.loading));
					progressDialog.show();
					error = null;
				} catch (Exception e) {
					error = e.getMessage();
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					String fileNames = "";
					JSONObject jo;
					ImageItem ii;
					for (int i = 0; i < files.size(); i++) {
						ii = files.get(i);
						if (ii.isFile) {
							jo = new JSONObject(
									HttpUtils
											.uploadImageFile(new File(ii.file)));
							if (i == 0) {
								fileNames = jo.getString("fn");
							} else {
								fileNames += "|" + jo.getString("fn");
							}
						} else {
							if (i == 0) {
								fileNames = ii.file;
							} else {
								fileNames += "|" + ii.file;
							}
						}

					}
					HttpUtils.updateAd(adId, text, phNo, fileNames);
				} catch (Exception e) {
					error = e.getMessage();
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					progressDialog.dismiss();
					if (error == null) {
						showUpdatedMessage();
					} else {
						Utils.showAlertMessage(EditAdActivity.this, null, error);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	public void showMarkedSoldMessage() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.marked_sold))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								backToHome();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	public void showUpdatedMessage() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.ad_updated))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								backToHome();
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	private void markSold() {
		try {
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;
				private String error;

				protected void onPreExecute() {
					try {
						progressDialog = Utils.getProgressDialog(
								EditAdActivity.this, null,
								getString(R.string.loading));
						progressDialog.show();
						error = null;
					} catch (Exception e) {
						error = e.getMessage();
						e.printStackTrace();
					}
				}

				protected String doInBackground(String... arg0) {
					try {
						HttpUtils.markSold(adId);
					} catch (Exception e) {
						error = e.getMessage();
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						progressDialog.dismiss();
						if (error == null) {
							showMarkedSoldMessage();
						} else {
							Utils.showAlertMessage(EditAdActivity.this, null,
									error);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void backToHome() {
		try {
			startActivity(new Intent(this, HomeActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void removeImage(final View view) {
		switch (view.getId()) {
		case R.id.image_item1:
			bitmaps.remove(0);
			files.remove(0);
			break;
		case R.id.image_item2:
			bitmaps.remove(1);
			files.remove(1);
			break;
		case R.id.image_item3:
			bitmaps.remove(2);
			files.remove(2);
			break;
		case R.id.image_item4:
			bitmaps.remove(3);
			files.remove(3);
			break;
		case R.id.image_item5:
			bitmaps.remove(4);
			files.remove(4);
			break;
		case R.id.image_item6:
			bitmaps.remove(5);
			files.remove(5);
			break;
		case R.id.image_item7:
			bitmaps.remove(6);
			files.remove(6);
			break;
		case R.id.image_item8:
			bitmaps.remove(7);
			files.remove(7);
			break;
		case R.id.image_item9:
			bitmaps.remove(8);
			files.remove(8);
			break;
		default:
			break;
		}
		showImages();
	}

	private void showImages() {
		ImageView imView = null;
		for (int i = 0; i < Constants.MAX_IMAGES; i++) {
			switch (i) {
			case 0:
				imView = (ImageView) images.findViewById(R.id.image_item1);
				break;
			case 1:
				imView = (ImageView) images.findViewById(R.id.image_item2);
				break;
			case 2:
				imView = (ImageView) images.findViewById(R.id.image_item3);
				break;
			case 3:
				imView = (ImageView) images.findViewById(R.id.image_item4);
				break;
			case 4:
				imView = (ImageView) images.findViewById(R.id.image_item5);
				break;
			case 5:
				imView = (ImageView) images.findViewById(R.id.image_item6);
				break;
			case 6:
				imView = (ImageView) images.findViewById(R.id.image_item7);
				break;
			case 7:
				imView = (ImageView) images.findViewById(R.id.image_item8);
				break;
			case 8:
				imView = (ImageView) images.findViewById(R.id.image_item9);
				break;
			default:
				break;
			}
			if (i < bitmaps.size()) {
				imView.setImageBitmap(bitmaps.get(i));
			} else {
				imView.setImageBitmap(null);
			}
		}
		if (bitmaps.size() > 0) {
			noticeView.setVisibility(View.GONE);
		} else {
			noticeView.setVisibility(View.VISIBLE);
		}
	}

	private void takePicture() {
		if (files.size() < Constants.MAX_IMAGES) {
			String fileName = Integer.toString(counter++);
			ContentValues values = new ContentValues();
			values.put(MediaStore.Images.Media.TITLE, fileName);
			values.put(MediaStore.Images.Media.DESCRIPTION,
					"Image capture by camera");
			imageUri = getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			startActivityForResult(intent, GET_IMAGE_BY_CAMERS);
		} else {
			Utils.showAlertMessage(this, null,
					getString(R.string.image_constraint_message));
		}
	}

	private void pickFromGallery() {
		if (files.size() < Constants.MAX_IMAGES) {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					GET_IMAGE_FROM_GALLERY);
		} else {
			Utils.showAlertMessage(this, null,
					getString(R.string.image_constraint_message));
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		Bitmap image = null;
		File file = null;
		String path = null;
		int imgWidth = (2 * getWindowManager().getDefaultDisplay().getWidth()) / 5;
		switch (requestCode) {
		case GET_IMAGE_BY_CAMERS:
			try {
				file = Utils.convertImageUriToFile(imageUri,
						EditAdActivity.this);
				path = file.getAbsolutePath();
				image = Utils.decodeFile(file, imgWidth, imgWidth);
			} catch (Exception e) {
				e.printStackTrace();
			}

			break;
		case GET_IMAGE_FROM_GALLERY:

			try {
				Uri selectedImageUri = data.getData();
				file = new File(Utils.getRealPathFromURI(selectedImageUri,
						EditAdActivity.this));
				path = file.getAbsolutePath();
				image = Utils.decodeFile(file, imgWidth, imgWidth);

			} catch (Exception e) {

				Toast.makeText(getApplicationContext(), e.toString(),
						Toast.LENGTH_LONG).show();
			}
			break;
		default:
			break;
		}
		if (image == null || file == null) {
			return;
		} else {
			bitmaps.add(image);
			files.add(new ImageItem(file.getPath(), true));
			showImages();
		}
	}

	class ImageItem {
		private String file;
		private boolean isFile;

		public ImageItem(String file, boolean isFile) {
			this.file = file;
			this.isFile = isFile;
		}
	}
}
